package com.gt.login.activities;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.gt.login.Constants;
import com.gt.login.FileUtils;
import com.gt.login.R;
import com.gt.login.SaxParserUser;
import com.gt.login.Session;
import com.gt.login.User;
import com.gt.login.UserUtil;

public class LoginPage extends Activity {
	/** Called when the activity is first created. */
	EditText userNameTXT;
	EditText passwordTXT;
	Button submitBtn;
	String XML_FILE = Constants.XML_FILE;
	String IP_USER_XML_DATA_PATH = Constants.IP_USER_XML_DATA_PATH;
	String OP_DATA_PATH = Constants.OP_DATA_PATH;

	List<User> users;
	String curUser;
	String pass;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		handleFirstRun();
		initComponents();
		readUsersFromXML();
		resetTXTFieldsOnBack();
	}
	@Override
	public void onBackPressed() {
		setResult(RESULT_CANCELED);
		finish();
	}
	private void handleFirstRun(){
		// mkDirs
		FileUtils.mkDir(IP_USER_XML_DATA_PATH);
		FileUtils.mkDir(OP_DATA_PATH);
		//asset copy
		FileUtils.CopyAssets(getAssets());
	}
	private void initComponents() {
		userNameTXT = (EditText) findViewById(R.id.userName);
		passwordTXT = (EditText) findViewById(R.id.password);
		submitBtn = (Button) findViewById(R.id.submitBtn);
		submitBtn.setOnClickListener(loginCL);
	}

	/**
	 * read registered users
	 */
	private void readUsersFromXML() {
		// parse xml
		SaxParserUser parser = new SaxParserUser(XML_FILE);
		users = parser.parseFileAndGetListOfUsers();
		System.out.println(users.toString());

	}

	/**
	 * set blanks
	 */
	private void resetTXTFieldsOnBack() {
		userNameTXT.setText("");
		passwordTXT.setText("");
	}

	OnClickListener loginCL = new View.OnClickListener() {

		@Override
		public void onClick(View arg0) {
			curUser = userNameTXT.getText().toString().trim();
			pass = passwordTXT.getText().toString().trim();

			if (curUser.equals("") || pass.equals("")) {
				showToast("Enter username and password properly");
				return;
			} else {
				loginUser();
			}
		}
	};

	private void loginUser() {
		User user = UserUtil.getUser(users, curUser);
		if (null == user) {
			showToast("INCORRECT USERNAME OR PASSWORD");
			return;
		}
		if (user.getUserName().equalsIgnoreCase(curUser)
				&& user.getPassword().equalsIgnoreCase(pass)) {
			// save in session
			Session ss = ((Session) getApplicationContext());
			ss.setLoggedInUser(user);
			// change to other screen
//			handleSuccessLogin();
//			changeToXmlDataBrowser();
			returnToListActivity();
		} else {
			showToast("INCORRECT USERNAME OR PASSWORD");
		}
	}

	private void returnToListActivity(){
		setResult(RESULT_OK);
		finish();
	}
	private void handleSuccessLogin() {
		// dialog at success
		AlertDialog.Builder builder = new AlertDialog.Builder(LoginPage.this);
		builder.setMessage("Login Success").setCancelable(true)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// changeToWelcomePage();
						changeToXmlDataBrowser();
					}

				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void showToast(String msg) {
		Toast toast;
		toast = Toast.makeText(LoginPage.this, msg, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
		toast.show();
	}

	private void changeToXmlDataBrowser() {
		Intent i = new Intent(LoginPage.this, FileListActivity.class);
		User user = UserUtil.getUser(users, curUser);
		// user object must be serializable
		i.putExtra("USER_DETAIL", user);
		startActivity(i);
	}

	private void changeToWelcomePage() {
		Intent i = new Intent(LoginPage.this, UserDetailViewEdit.class);
		User user = UserUtil.getUser(users, curUser);
		// user object must be serializable
		i.putExtra("USER_DETAIL", user);
		startActivity(i);
	}

}